package com.lzy.wzy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class JwtTokenReConfig {

    @Bean(name = "jwtTokenStoreRe")
    public TokenStore jwtTokenStoreRe() {
        return new JwtTokenStore(jwtAccessTokenConverterRe());
    }

    @Bean(name = "jwtAccessTokenConverterRe")
    public JwtAccessTokenConverter jwtAccessTokenConverterRe() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //jwtAccessTokenConverter.setSigningKey("wylwzy");
        jwtAccessTokenConverter.setVerifierKey(getPublicKey());
        return jwtAccessTokenConverter;
    }

    private String getPublicKey() {
        ClassPathResource resource = new ClassPathResource("publickey.txt");
        try (InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
             BufferedReader br = new BufferedReader(inputStreamReader)) {
            return br.lines().collect(Collectors.joining("\n"));
        } catch (IOException ioe) {
            return null;
        }
    }
}
